package com.mdnote.structure.treebaswe;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/29
 * @description 数基础 二叉树遍历
 */
public class BinaryTreeOrder {

    /**
     * 节点
     */
    private static class Node {
        private int value;
        private Node left;
        private Node right;

        public Node(int value) {
            this.value = value;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public void setRight(Node right) {
            this.right = right;
        }

        /**
         * 谦虚遍历
         */
        private void preOrder() {
            System.out.print(this.value + " ");
            if (this.left != null) {
                this.left.preOrder();
            }
            if (this.right != null) {
                this.right.preOrder();
            }
        }

        /**
         * 终须遍历
         */
        private void infixOrder() {
            if (this.left != null) {
                this.left.infixOrder();
            }
            System.out.print(this.value + " ");
            if (this.right != null) {
                this.right.infixOrder();
            }
        }

        /**
         * 后续遍历
         */
        private void postOrder() {
            if (this.left != null) {
                this.left.postOrder();
            }
            if (this.right != null) {
                this.right.postOrder();
            }
            System.out.print(this.value + " ");
        }
    }

    public Node root;

    public BinaryTreeOrder(Node root) {
        this.root = root;
    }

    private void preOrder() {
        root.preOrder();
    }

    private void infixOrder() {
        root.infixOrder();
    }

    private void postOrder() {
        root.postOrder();
    }


    public static void main(String[] args) {
        Node node1 = new Node(11);
        Node node2 = new Node(22);
        Node node3 = new Node(33);
        Node node4 = new Node(44);
        Node node5 = new Node(55);


        node1.setLeft(node2);
        node1.setRight(node3);
        node2.setLeft(node4);
        node2.setRight(node5);

        BinaryTreeOrder binaryTreeOrder = new BinaryTreeOrder(node1);
        System.out.println("前序遍历");
        // 应该是 11 22 44 55 33
        binaryTreeOrder.preOrder();
        System.out.println();
        System.out.println("中序遍历");
        // 应该是 44 22 55 11 33
        binaryTreeOrder.infixOrder();
        System.out.println();
        System.out.println("后序遍历");
        // 应该是 44 55 22 33 11
        binaryTreeOrder.postOrder();
    }
}
